import React, { useState, useEffect } from 'react';
import { Menu } from 'antd';
import RouterList from '../../routers/Menu';
import { useLocation, useNavigate } from 'react-router-dom';
function getItem(label, key, icon, children, type) {
  return {
    key,
    icon,
    children,
    label,
    type,
  };
}

function getTree(data) {
  let tree = [];
  for (let i = 0; i < data.length; i++) {
    let item = data[i];
    let children = item.children;
    if (children && children.length > 0) {
      let childrenTree = getTree(children);
      tree.push(getItem(item.meta.title, item.path, item.meta.icon, childrenTree, item.element));
      continue;
    }
    tree.push(getItem(item.meta.title, item.path, item.meta.icon, null, item.element));
  }
  return tree;
}
const items = getTree(RouterList);
const rootSubmenuKeys = RouterList.map((item) => item.path);
const App = () => {
  const [activeName, setactiveName] = useState('/home');
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    setactiveName(location.pathname)
  }, []);
  const [openKeys, setOpenKeys] = useState([RouterList[0].path]);
  const onOpenChange = (keys) => {
   //
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
   // console.log(latestOpenKey);
    if (latestOpenKey && rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys);
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  };
  const getkeyPath = (e) => {
    setactiveName(e.key)
    navigate(e.key)
  }
  return (
    <Menu
      mode="inline"
      openKeys={openKeys}
      onOpenChange={onOpenChange}
      style={{
        width: 200,
      }}
      items={items}
      onClick={getkeyPath}
      defaultOpenKeys={[activeName]}
      selectedKeys={[activeName]}
      defaultSelectedKeys={[activeName]}
    />
  );
};
export default App;